package hotel.switchs.oversea.biz.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import hotel.base.oversea.constant.CallbackConstants;
import hotel.base.oversea.constant.CommonConstants;
import hotel.base.oversea.utils.DateUtil;
import hotel.base.oversea.utils.Result;
import hotel.switchs.oversea.api.VO.request.SetRoomOnlineOfflineVo;
import hotel.switchs.oversea.api.entity.SwitchCreateRoomEntity;
import hotel.switchs.oversea.api.entity.SwitchCreateRoomFailureEntity;
import hotel.switchs.oversea.api.entity.SwitchRefuseOrderListEntity;
import hotel.switchs.oversea.biz.config.service.RedisService;
import hotel.switchs.oversea.biz.mapper.SwitchCreateRoomFailureMapper;
import hotel.switchs.oversea.biz.mapper.SwitchCreateRoomMapper;
import hotel.switchs.oversea.biz.mapper.SwitchRefuseOrderListMapper;
import hotel.switchs.oversea.biz.service.SwitchBasicRoomTypeService;
import hotel.switchs.oversea.biz.service.SwitchRoomPriceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 便捷操作工具
 * @Author lmf
 * @Date 2020/6/10 13:39
 **/
@Slf4j
@RestController
@RequestMapping("/switchTool")
@Api(value = "SwitchToolController",tags = {"便捷操作工具"})
public class SwitchToolController {
    @Autowired
    RedisService redisService;
    @Autowired
    SwitchRefuseOrderListMapper switchRefuseOrderListMapper;
    @Autowired
    SwitchCreateRoomMapper switchCreateRoomMapper;
    @Autowired
    SwitchBasicRoomTypeService switchBasicRoomTypeService;
    @Autowired
    SwitchCreateRoomFailureMapper switchCreateRoomFailureMapper;
    @Autowired
    SwitchRoomPriceService switchRoomPriceService;
    @Autowired
    RedisTemplate redisTemplate;
    /**
     * 刪除緩存/增加緩存
     */
    @PostMapping("/operaCache")
    @ApiOperation(value = "操作緩存相關操作 ",notes="必须经过auth授权")
    public Result<Object> operaCache(@RequestBody JSONObject jsonObject){
        int db=jsonObject.getInteger("db");
        String key=jsonObject.getString("key");
        int genre=jsonObject.getInteger("genre");
        /**
         * 增加緩存/更新緩存/获取缓存
         */
        Object object=null;
        if(genre==1){
            String value=jsonObject.getString("value");
            redisService.set(db,key,value);
        }else if(genre==0) {
            object=redisService.get(key);
        }else if(genre==2){
            String value=jsonObject.getString("value");
            redisService.set(db,key,Integer.valueOf(value));
        }else{//刪除緩存
            if(redisService.exists(key)){
                redisService.remove(db,key);
            }
        }
        return new Result<>(object);
    }


    /**
     * 拒單率統計
     */
    @PostMapping("/addOrder")
    @ApiOperation(value = "拒單率統計 ",notes="必须经过auth授权")
    public Result<Object> addOrder(@RequestBody SwitchRefuseOrderListEntity switchRefuseOrderListEntity){
        Example example=new Example(SwitchRefuseOrderListEntity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("time",switchRefuseOrderListEntity.getTime());
        SwitchRefuseOrderListEntity switchRefuseOrderListEntity1=switchRefuseOrderListMapper.selectOneByExample(example);
        if(!ObjectUtil.isEmpty(switchRefuseOrderListEntity1)){
           return new Result<>("不能重复添加");
        }
        switchRefuseOrderListEntity.setCreateTime(new Date());
        int flag=switchRefuseOrderListMapper.insert(switchRefuseOrderListEntity);
        if(flag>0){
            Map map=switchRefuseOrderListMapper.selectRefudeRate();
            int total= Integer.valueOf(String.valueOf( map.get("total")));
            double rate= Double.valueOf(String.valueOf(map.get("rate")));
            int refudeNum= (int) ((0.05-rate)*total);
            return new Result<>(refudeNum);
        }else{
            return new Result<>("新增失败");
        }
    }
    @PostMapping("/orderList")
    @ApiOperation(value = "拒單率統計 ",notes="必须经过auth授权")
    public Result<Object> orderList(){
        PageHelper.startPage(1, 13);
        List<SwitchRefuseOrderListEntity> list = switchRefuseOrderListMapper.selectRefudeList();
        int total=0;
        int refude=0;
        for(SwitchRefuseOrderListEntity switchRefuseOrderListEntity:list){
            total+=switchRefuseOrderListEntity.getTotal();
            refude+=switchRefuseOrderListEntity.getFlaw();
        }
        int refudeNum= (int) ((0.05-refude/total)*total);
        PageInfo<SwitchRefuseOrderListEntity> pageInfo = new PageInfo<>(list);
        return new Result<>(pageInfo,String.valueOf(refudeNum));
    }

    @PostMapping("/delOrder")
    @ApiOperation(value = "删除订单 ",notes="必须经过auth授权")
    public Result<Object> delOrder(@RequestBody SwitchRefuseOrderListEntity switchRefuseOrderListEntity){
        Example example=new Example(SwitchRefuseOrderListEntity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("id",switchRefuseOrderListEntity.getId());
        int flag=switchRefuseOrderListMapper.deleteByExample(example);
        Map map=switchRefuseOrderListMapper.selectRefudeRate();
        int total= Integer.valueOf(String.valueOf( map.get("total")));
        double rate= Double.valueOf(String.valueOf(map.get("rate")));
        int refudeNum= (int) ((0.05-rate)*total);
        if(flag>0){
            return new Result<>(refudeNum);
        }else{
            return new Result<>("删除失败",refudeNum);
        }
    }

    @PostMapping("/upRoom")
    @ApiOperation(value = "删除订单 ",notes="必须经过auth授权")
    public Result<Object> upRoom(){
        List<SwitchCreateRoomEntity> switchCreateRoomEntities=switchCreateRoomMapper.selectAllData();
        for(SwitchCreateRoomEntity switchCreateRoomEntity:switchCreateRoomEntities){
            SetRoomOnlineOfflineVo setRoomOnlineOfflineVo=new SetRoomOnlineOfflineVo();
            setRoomOnlineOfflineVo.setRoomTypeId(switchCreateRoomEntity.getRoomId());
            setRoomOnlineOfflineVo.setHotelId(switchCreateRoomEntity.getHotelId());
            setRoomOnlineOfflineVo.setChannel("Ctrip");
            setRoomOnlineOfflineVo.setRoomStatus(1);
            switchBasicRoomTypeService.setRoomOnlineOffline(setRoomOnlineOfflineVo);
            setRoomOnlineOfflineVo.setChannel("Qunar");
            switchBasicRoomTypeService.setRoomOnlineOffline(setRoomOnlineOfflineVo);
        /*    try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }*/
        }
       return new Result<>();
    }

    /***
    * @Author: lmf
    * @Date: 2020/11/30
     * 清除缓存,清黑名单的酒店+下线的酒店
    */
    @GetMapping("/delRoomCache")
    @ApiOperation(value = "清除缓存 ",notes="必须经过auth授权")
    public Result<Object> delRoomCache(@RequestParam(value = "genre",defaultValue = "0")Integer genre){
        //清除黑名单缓存
        List<SwitchCreateRoomEntity> switchCreateRoomEntities=new ArrayList<>();
        if(genre==0){
            switchCreateRoomEntities=switchCreateRoomMapper.selectHotelUpStatus(2);
        }else{//1.清除下线的酒店缓存
           switchCreateRoomEntities=switchCreateRoomMapper.selectHotelUpStatus(0);
        }
        for(SwitchCreateRoomEntity switchCreateRoomEntity:switchCreateRoomEntities){
            //清除与售卖房型的关联数据
            String key= CommonConstants.SWITCH_SELLING_REDIS_BY_MT+switchCreateRoomEntity.getMtHotelId()+"_"+switchCreateRoomEntity.getMtGoodId();
            if(redisService.exists(key)){
                redisService.remove(key);
            }
            //清除美团酒店id+美团产品id的key
            key=CommonConstants.SWITCH_SELLING_THE_HOUSE_TYPE+switchCreateRoomEntity.getMtHotelId()+"_"+switchCreateRoomEntity.getMtGoodId();
            if(redisService.exists(key)){
                redisService.remove(key);
            }
            //清除美团酒店id+美团房型id
            key=CommonConstants.SWITCH_SELLING_THE_HOUSE_ROOM_TYPE+switchCreateRoomEntity.getMtHotelId()+"_"+switchCreateRoomEntity.getMtRoomId();
            if(redisService.exists(key)){
                redisService.remove(key);
            }
            //清除美团酒店id+美团产品id+餐食
            key=CommonConstants.SWITCH_CREATE_ROOM_BREAKFAST+switchCreateRoomEntity.getMtHotelId()+"_"+switchCreateRoomEntity.getMtRoomId()+"_0";
            if(redisService.exists(key)){
                redisService.remove(key);
            }
            key=CommonConstants.SWITCH_CREATE_ROOM_BREAKFAST+switchCreateRoomEntity.getMtHotelId()+"_"+switchCreateRoomEntity.getMtRoomId()+"_1";
            if(redisService.exists(key)){
                redisService.remove(key);
            }
        }
        return new Result<>();
    }
    /****
    * @Author: lmf
    * @Date: 2020/12/22
     * 删除失效产品的缓存信息
    */
    @GetMapping("/deleteRoomFailure")
    @ApiOperation(value = "删除房态价格的缓存",notes="必须经过auth授权")
    public Result<Object> deleteRoomFailure(){
        List<SwitchCreateRoomFailureEntity> switchCreateRoomFailureEntities=switchCreateRoomFailureMapper.deleteRoomFailure();
        for(SwitchCreateRoomFailureEntity switchCreateRoomFailureEntity:switchCreateRoomFailureEntities){
            String key=CallbackConstants.REDIS_ROW_GOODS_PRICE_CHECK+switchCreateRoomFailureEntity.getMtHotelId()+"_"+switchCreateRoomFailureEntity.getMtGoodId();
            if(redisService.exists(key)){
                log.info("======key {}删除中=========",key);
                redisService.remove(key);
            }else{
                log.info("======key {}忽略=========",key);
            }
            key=CallbackConstants.REDIS_ROW_GOODS_STATUS_CHECK+switchCreateRoomFailureEntity.getMtHotelId()+"_"+switchCreateRoomFailureEntity.getMtGoodId();
            if(redisService.exists(key)){
                log.info("======key {}删除中=========",key);
                redisService.remove(key);
            }else{
                log.info("======key {}忽略=========",key);
            }
            int day=3;
            //删除价格和房态缓存
            for(int i=0;i<day;i++){
                //删除房态
                key=CallbackConstants.REDIS_KEY_CALLBACK_CHANGE_STATUS_HEAD+switchCreateRoomFailureEntity.getMtHotelId()+"_"+switchCreateRoomFailureEntity.getMtGoodId()+"_"+DateUtil.getDateAfter(new Date(),i);
                if(redisService.exists(key)){
                    log.info("======key {}删除中=========",key);
                    redisService.remove(key);
                }else{
                    log.info("======key {}忽略=========",key);
                }
                //删除价格
                key=CallbackConstants.REDIS_KEY_CALLBACK_CHANGE_PRICE_HEAD+switchCreateRoomFailureEntity.getMtHotelId()+"_"+switchCreateRoomFailureEntity.getMtGoodId()+"_"+DateUtil.getDateAfter(new Date(),i);
                if(redisService.exists(key)){
                    log.info("======key {}删除中=========",key);
                    redisService.remove(key);
                }else{
                    log.info("======key {}忽略=========",key);
                }
                //删除价格
                key=CallbackConstants.REDIS_KEY_CALLBACK_CHANGE_PRICE_HEAD+switchCreateRoomFailureEntity.getMtHotelId()+"_"+switchCreateRoomFailureEntity.getMtGoodId()+"_"+DateUtil.getDateAfter(new Date(),i);
                if(redisService.exists(key)){
                    log.info("======key {}删除中=========",key);
                    redisService.remove(key);
                }else{
                    log.info("======key {}忽略=========",key);
                }
            }
        }
        return new Result<>();
    }

}
